package cn.lutu.domain.service.impl;

import cn.lutu.domain.repository.ArticleRepository;
import cn.lutu.domain.repository.CommentRepository;
import cn.lutu.domain.service.CommentService;

import cn.lutu.protocol.dto.CommentPostDTO;
import cn.lutu.protocol.entity.Article;
import cn.lutu.protocol.entity.Comment;
import cn.lutu.protocol.vo.CommentVO;
import cn.lutu.security.jwtFilter.CurrentPrincipal;
import cn.lutu.util.exception.ServiceException;
import cn.lutu.util.response.StatusCode;
import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    ArticleRepository articleRepository;
    @Override
    public Comment insert(CommentPostDTO commentPostDTO, CurrentPrincipal currentPrincipal) {
        if(articleRepository.selectArticleDetail(commentPostDTO.getArticleId()) == null){
            String message = "你所评论的文章不存在,请重新提交!";
            log.debug(message);
            throw new ServiceException(StatusCode.ERROR_NOT_FOUND,message);
        }
        String data = commentPostDTO.getContent().trim();

        if(data == null || data == "" || data.isEmpty()){
            String message = "评论失败,评论内容不能为空!";
            log.debug(message);
            throw new ServiceException(StatusCode.ERROR_TITLE_NULL,message);
        }

        String content = commentPostDTO.getContent();
        boolean contains = SensitiveWordBs.newInstance().contains(content);
        if(contains){
            String message = "您发布的评论包含敏感词汇,请重新编辑并提交";
            log.debug(message);
            throw new ServiceException(StatusCode.OPERATION_FAILED,message);
        }

        Comment comment = new Comment();
        BeanUtils.copyProperties(commentPostDTO,comment);
        comment.setContent(commentPostDTO.getContent());
        comment.setArticleId(commentPostDTO.getArticleId());
        comment.setParentId(commentPostDTO.getParentId());
        comment.setUserId(currentPrincipal.getId());
        commentRepository.insert(comment);

        Article article = new Article();
        log.debug("正在处理修改评论业务");
        article.setId(commentPostDTO.getArticleId());
        article.setCommentCount(articleRepository.selectArticleDetail(commentPostDTO.getArticleId()).getCommentCount()+1);
        articleRepository.updateCollect(article);
        return comment;
    }

    @Override
    public List<CommentVO> selectById(Long id) {
        log.debug("正在处理获取评论列表业务",id);
        List<CommentVO> list = commentRepository.selectById(id);
        return list;
    }

    @Override
    public void deleteById(Long id) {
        log.debug("正在处理删除评论业务",id);
        commentRepository.deleteById(id);
    }


}
